package com.example.demo.service;

import com.example.demo.domain.Ebook;
import com.example.demo.domain.EbookExample;
import com.example.demo.req.EbookSaveReq;
import com.example.demo.mapper.EbookMapper;
import com.example.demo.req.EbookQueryReq;
import com.example.demo.resp.EbookQueryResp;
import com.example.demo.resp.PageResp;
import com.example.demo.util.CopyUtil;
import com.example.demo.util.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;


@Service
public class EbookService {

    private static final Logger LOG = (Logger) LoggerFactory.getLogger(EbookService.class);
    @Resource
    private EbookMapper ebookMapper;

    /**
     * @Resource  是jdk自带 @Autowired是Spring自带的
     * */
    @Resource
    private SnowFlake snowFlake;

    public PageResp<EbookQueryResp> list(EbookQueryReq req){

        EbookExample ebookExample=new EbookExample();
        EbookExample.Criteria criteria= ebookExample.createCriteria();
        if (!ObjectUtils.isEmpty(req.getName())) {
            criteria.andNameLike("%" + req.getName() + "%");
        }

        if (!ObjectUtils.isEmpty(req.getCategoryId2())) {
            criteria.andCategory1IdEqualTo( req.getCategoryId2());
        }

        PageHelper.startPage(req.getPage(),req.getSize());
        List<Ebook>ebookList= ebookMapper.selectByExample(ebookExample);

        PageInfo<Ebook> pageInfo = new PageInfo<>(ebookList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());


        //列表复制
        List<EbookQueryResp> list=CopyUtil.copyList(ebookList, EbookQueryResp.class);
        PageResp<EbookQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageResp.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    /**
     * 保存
    * */
    public void save(EbookSaveReq req){
        Ebook ebook=CopyUtil.copy(req,Ebook.class);
        if(ObjectUtils.isEmpty(req.getId())){
            //新增
            ebook.setId(snowFlake.nextId());
            ebookMapper.insert(ebook);
        }else{
            //更新
            ebookMapper.updateByPrimaryKey(ebook);
        }

    }
    public void  delete(Long id){
        ebookMapper.deleteByPrimaryKey(id);
    }
}
/**
 * id算法
 *    简单的自增
 *    uuid
 *    雪花算法
* */